package com.smart.config;

import com.smart.shiro.AuthenticationFormConfig;
import com.smart.shiro.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //注册加密器
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(3);
        matcher.setHashAlgorithmName("md5");
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

//    //注册自定义cookie用于自动登录
//    @Bean
//    public SimpleCookie simpleCookie() {
//        SimpleCookie cookie = new SimpleCookie();
//        cookie.setName("rememberMe");
//        cookie.setMaxAge(604800);     //设置保存7天
//        cookie.setHttpOnly(true);
//        return cookie;
//    }
//
//    //设置“记住我”管理器
//    @Bean
//    public CookieRememberMeManager cookieRememberMeManager(SimpleCookie rememberCookie) {
//        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
//        rememberMeManager.setCookie(rememberCookie);
//        return rememberMeManager;
//    }

    //注册安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(MyRealm realm,
                                                               HashedCredentialsMatcher matcher) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        realm.setCredentialsMatcher(matcher);
        manager.setRealm(realm);
//        manager.setRememberMeManager(rememberMeManager);
        ThreadContext.bind(manager);
        return manager;
    }

    //注册Shiro工厂Bean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        Map<String, String> map = new HashMap<>();
        map.put("/upload", "anon");
        map.put("/uploadPic", "anon");
        map.put("/user/getCode", "anon");
        map.put("/user/resetPassword", "anon");
        map.put("/user/login", "anon");
        map.put("/**", "authc");

        factoryBean.setFilterChainDefinitionMap(map);
        factoryBean.getFilters().put("authc", new AuthenticationFormConfig());  //自定义登录表单管理器，排除option复杂请求

        return factoryBean;
    }
}
